package com.touch.jgloo.core;
import java.awt.*;
import java.io.*;
import java.util.*;
import com.touch.jgloo.JGLTextureLoader;
import com.touch.jgloo.owt.JGLSprite;
import com.touch.util.JarReader;
import com.sun.opengl.util.texture.*;
/**
 * A text Objet that uses Texture font to render to the screen. Unlike Stroke font, 
 * Texture font is always supported. In addition, Texture font allows customization. However,
 * It does use more memory.
 * @author Homicidal Monkey
 * @version 10.1.13
 * @since r461
 * @see com/touch/Licence
 */
public class TextureText extends JGLTextObject
{
	/**
	 * Texture used for the font
	 * @since r461
	 */
	public static Texture FONTTEXTURE;
	//sprites representing the chars of the font
	private final Vector <JGLSprite> text = new Vector <JGLSprite>();
	
	static
	{
		//file representing the graphics file
		final File graphicsJAR = new File("graphics.zip");
		//file representing the font
		final File fontIMG = new File("font");
		
		//if the graphics file exists
		if(graphicsJAR.exists())
		{
			//create a zip reader
			final JarReader r = new JarReader("graphics.zip");
			//open the font file
			final InputStream fontStream = r.openStream("font");
			//create the text file from the font
			FONTTEXTURE = JGLTextureLoader.loadIMG(fontStream, false, null);			
		}
		//if the image exists
		else if(fontIMG.exists())
		{
			try 
			{
				//create the texture from the font file
				FONTTEXTURE = JGLTextureLoader.loadIMG(new FileInputStream(fontIMG), false, null);
			}
			catch (FileNotFoundException e) 
			{			
				e.printStackTrace();
			}
		}				
	}	
	public TextureText(){}	
	public TextureText(final String caption)
	{
		this.setCaption(caption);
	}
	@Override
	public synchronized void setCaption(final String caption)
	{		
		super.setCaption(caption);
		text.clear();
		
		for(int i = 0; i < caption.length(); i++)
		{
			final JGLSprite chr = new JGLSprite();
			
			char character = caption.charAt(i);
			character -= 32;
			
			//get the point of the character across
			final int x = character % 16; 
			//get the point of the character down
			final int y = character / 16;
			
			chr.setTexture(FONTTEXTURE, 16, 16);
			chr.setSprite(x, y);
			chr.setColor(this.getColor());
			text.add(chr);			
		}		
	}
	@Override
	public final synchronized void setTexture(final Texture texture)
	{
		//determine if the texture is not nothing
		if(texture == null)		
			//if the texture does not exist, then return
			return;
		else		
			//set the font texture
			FONTTEXTURE = texture;		
	}
	public final void render()
	{	
		//push the matrix up one
		GL_INSTANCE.glPushMatrix();
			//render each character
			for(JGLSprite chr: text)
			{
				chr.render();
				GL_INSTANCE.glTranslatef(10, 0, 0);	
			}			
		//push the matrix down one
		GL_INSTANCE.glPopMatrix();
	}
	@Override
	public final void setColor(final Color color)
	{
		super.setColor(color);
		for(JGLSprite chr: text)
			chr.setColor(color);
	}			
}